import { getMosThemecolor } from "@/apis/paas/MosEndpoint.js";
import stores from "store2";
import config from "./theme.config.json";
import { MOS_ENABLED } from "@/utils/const";
const COLOR_KEY = "color";
const HANCODE_THEME_KEY = "_hancode_theme_";
const THEME_ID_PREFIX = "_hancode_theme_";

export const THEME_COLOR_ENUM = config.themes.map((theme) =>
  theme.color.toLocaleLowerCase()
);
export const DEFAULT_THEME_COLOR = THEME_COLOR_ENUM[0];

/**
 * 设置css变量
 * @param {} theme
 */
function setCssVar(theme = {}) {
  let root = document.documentElement;
  Object.keys(theme).forEach((key) => {
    const varName = `--hancode-${key.replace(/([A-Z])/g, "-$1").toLowerCase()}`;
    root.style.setProperty(varName, theme[key]);
  });
}

class ThemeUtil {
  /**
   * 初始化
   */
  static async init() {
    let primaryColor = this.getColor();
    this.setColor(primaryColor);
    const inPortal = stores.get(MOS_ENABLED);
    if (inPortal) {
      // 获取portal颜色配置
      const color = await getMosThemecolor();
      this.setColor(color);
    }
  }

  /**
   * 获取当前主题色
   * @returns
   */
  static getColor() {
    const theme = stores.get(HANCODE_THEME_KEY) || {};
    return theme[COLOR_KEY] || DEFAULT_THEME_COLOR;
  }

  /**
   * 设置主题色
   * @param {*} color
   * @returns
   */
  static setColor(color = "") {
    if (!color || !THEME_COLOR_ENUM.includes(color)) {
      return;
    }

    document
      .querySelectorAll(`link[id^="${THEME_ID_PREFIX}"]`)
      .forEach((link) => {
        link.remove();
      });

    let theme = stores.get(HANCODE_THEME_KEY) || {};
    theme[COLOR_KEY] = color;
    stores.set(HANCODE_THEME_KEY, theme);

    const name = color.replace("#", "");
    const id = `${THEME_ID_PREFIX}${name}`;
    const dom = document.getElementById(id);
    if (dom) return;
    const link = document.createElement("link");
    link.id = id;
    link.rel = "stylesheet";
    link.href = process.env.VUE_APP_ROOT_URL + `/theme/style.${name}.css`;
    document.querySelector("head").appendChild(link);

    const themeData = config.themes.find(theme => theme.color.toLocaleLowerCase() === color)
    setCssVar(themeData);
  }
}

export default ThemeUtil;
